﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using tscmcnet;

namespace CS_ThicknessDemo
{
    public partial class Form1 : Form
    {
        //通信类
        TSCMCAPINET protocol;
        int controller_idx;//控制器编号
        const int data_size = 100;//数据大小
        DataNode[] dataNode;//数据

        public delegate void AddLogHandler(string log);
        public AddLogHandler AddLogEventHandler;
        public delegate void AddDataHandler(DataNode[] data);
        public AddDataHandler AddDataEventHandler;



        public Form1()
        {
            InitializeComponent();

            //通信类
            protocol = new TSCMCAPINET();
            bool res = SetConfiguration(Convert.ToInt32(txtLocalPort.Text), txtDstIp.Text, Convert.ToInt32(txtDstPort.Text));
            //各通道选择输出的数据为厚度

            //ERRCODE err = protocol.SetConfigOutputSignals(controller_idx, 3, CONNECTION_TYPE.ETHERNET, data_selection.ToArray());
            if (res)
            {
                AddLogEventHandler?.Invoke("设置通信类型位以太网");
                AddLogEventHandler?.Invoke("设置参数成功");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            AddLogEventHandler += AddLog;
            AddDataEventHandler += AddDataLog;
        }

        private void AddLog(string log)
        {
            this.Invoke(new Action(() =>
            {
                string timeStr = DateTime.Now.ToString("HH:mm:ss:fff");
                string content = $"·{log}:{timeStr}";
                txtLog.AppendText(content + "\r\n");
            }));

        }

        private void AddDataLog(DataNode[] data)
        {
            Task.Run(() =>
            {
                for (int i = 0; i < data.Length; i++)
                {
                    this.Invoke(new Action(() =>
                    {
                        txtData.AppendText($"·[{i}]:{data[i].cfg.channel}:{data[i].data}+\r\n");
                    }));
                }
            });
        }

        /// <summary>
        /// 设置配置
        /// </summary>
        /// <param name="localPort"></param>
        /// <param name="dstIp"></param>
        /// <param name="dstPort"></param>
        /// <returns></returns>
        public bool SetConfiguration(int localPort, string dstIp, int dstPort)
        {
            controller_idx = 0;
            protocol.SetConnectionType(CONNECTION_TYPE.ETHERNET);
            //设置本地网口监听端口
            protocol.SetUdpPort(localPort);
            //设置要连接的下位机IP地址与通信端口
            bool result = protocol.SetDestUdpEndPoint(dstIp, dstPort);
            return result;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            AddLogEventHandler?.Invoke("打开连接通道");
            bool result = protocol.OpenConnectionPort();
            if (result)
            {
                AddLogEventHandler?.Invoke("连接通道打开正常");
            }
            else
            {
                AddLogEventHandler?.Invoke("连接通道打开异常");
            }

        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            AddLogEventHandler?.Invoke("关闭连接通道");
            bool result = protocol.CloseConnectionPort();
            if (result)
            {
                AddLogEventHandler?.Invoke("关闭通道打开正常");
            }
            else
            {
                AddLogEventHandler?.Invoke("关闭通道打开正常");
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            AddLogEventHandler?.Invoke("建立连接");
            ERRCODE err = protocol.SetConnectionOn(controller_idx);

            List<int> data_selection = new List<int>();
            data_selection.Add((int)SENSOR_OUTPUT_DATA.THICKNESS);
            Console.Write("选择输出数据");

            if (err == ERRCODE.OK)
            {
                for (int i = 0; i < 4; i++)
                {
                    Thread.Sleep(100);
                    protocol.SetConfigOutputSignals(controller_idx, i + 1, CONNECTION_TYPE.ETHERNET, data_selection.ToArray());
                }
                AddLogEventHandler?.Invoke("建立连接正常");
            }
            else
            {
                protocol.CloseConnectionPort();
                AddLogEventHandler?.Invoke("建立连接异常，正在关闭通道");
            }
        }

        private void btnStartMeasure_Click(object sender, EventArgs e)
        {
            ERRCODE err;
            err = protocol.SetDataOutputOn(controller_idx);//开始连续测量
            if (err == ERRCODE.OK)
            {
                AddLogEventHandler?.Invoke("正在开始连续测量");
            }
            else
            {
                AddLogEventHandler?.Invoke("连续测量异常，关闭通道");
                protocol.CloseConnectionPort();
            }

            if (err == ERRCODE.OK)
            {
                AddLogEventHandler?.Invoke("数据读取正常");
                //AddDataEventHandler?.Invoke(dataNode);
            }
            else
            {
                AddLogEventHandler?.Invoke("读取异常，关闭通道");
                protocol.CloseConnectionPort();
            }
        }

        private void btnCloseMeasure_Click(object sender, EventArgs e)
        {
            /*从缓存区中读取数据*/
            Thread.Sleep(200);
            //data = new double[] { };
            dataNode = new DataNode[1000000];
            //err = protocol.TransferData(ref dataNode, data_size);
            //err = protocol.TransferDataNode(ref dataNode, 1000);
            protocol.TransferAllDataNode(ref dataNode, 1000000);
            //停止连续测量
            ERRCODE err = protocol.SetDataOutputOff(controller_idx);
            if (err == ERRCODE.OK)
            {
                AddLogEventHandler?.Invoke("停止连续测量正常");
                AddDataEventHandler?.Invoke(dataNode);
            }
            else
            {
                AddLogEventHandler?.Invoke("停止连续测量异常，关闭通道");
                protocol.CloseConnectionPort();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            AddLogEventHandler?.Invoke("断开连接");
            ERRCODE err = protocol.SetConnectionOff(controller_idx);
            if (err == ERRCODE.OK)
            {
                AddLogEventHandler?.Invoke("断开连接正常");
            }
            else
            {
                protocol.CloseConnectionPort();
                AddLogEventHandler?.Invoke("断开连接异常，正在关闭通道");
            }
        }

        private void btnClearData_Click(object sender, EventArgs e)
        {
            txtData.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string filePath = @"data\" + DateTime.Now.ToString("HHmmssfff") + ".txt";
            File.WriteAllText(filePath, txtData.Text);
            AddLogEventHandler?.Invoke($"写入本地：{filePath} 成功");
        }

        private void btnParse_Click(object sender, EventArgs e)
        {
            FrmParse.Instance.Show();
        }
    }
}
